import React from 'react';
import { inject, observer } from 'mobx-react';
import { WeaTableNew } from 'comsMobx';

let WeaTable = WeaTableNew.WeaTable;
import {
  WeaTop,
  WeaTab,
  WeaRightMenu,
  WeaErrorPage,
  WeaTools,
  WeaLocaleProvider,
  WeaPopoverHrm,
} from 'ecCom';
import { Button, Modal } from 'antd';
import CoworkConstant from '../util/CoworkConstant';
import * as CoworkUtil from '../util/CoworkUtil';
import { toJS } from 'mobx';

const confirm = Modal.confirm;
const getLabel = WeaLocaleProvider.getLabel;
const { viewer } = WeaTools;

/**
 * 收藏的帖子页面
 */
@inject('coworkCollectStore')
@observer
class Collect extends React.Component {
  constructor(props) {
    super(props);
  }
  componentDidMount() {
    this.props.coworkCollectStore.doInit();
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.location.key !== nextProps.location.key) {
      this.props.coworkCollectStore.doInit();
    }
  }

  componentWillUnmount() {
    // 组件卸载时一般清理一些状态
    const { coworkCollectStore } = this.props;
    coworkCollectStore.setShowSearchAd(false);
    coworkCollectStore.clearFormFields();
  }

  render() {
    const { coworkCollectStore } = this.props;
    const {
      comsWeaTableStore,
      loading,
      form,
      conditioninfo,
      showSearchAd,
      sessionkey,
    } = coworkCollectStore;
    const buttonsAd = [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@e9jlvn@search`}
        type="primary"
        onClick={this.onTabSearch}
      >
        {getLabel(197, '搜索')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@9f91ed@reset`}
        type="ghost"
        onClick={this.onTabReset}
      >
        {getLabel(2022, '重置')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@ecxrbq@cancel`}
        type="ghost"
        onClick={this.onTabCancel}
      >
        {getLabel(201, '取消')}
      </Button>,
    ];

    return (
      <div className="wea-cowork-collect">
        <WeaPopoverHrm
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaPopoverHrm@3g7off`}
        />

        <WeaRightMenu
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaRightMenu@b190e0`}
          datas={this.getRightMenu()}
          onClick={this.onRightMenuClick}
        >
          <WeaTop
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaTop@7vbzr7`}
            title={getLabel(382666, '收藏的帖子')}
            loading={loading}
            icon={CoworkConstant.icon}
            iconBgcolor={CoworkConstant.iconBgColor}
            buttons={this.getTopButtons()}
            buttonSpace={10}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
            onDropMenuClick={this.onRightMenuClick}
          >
            <WeaTab
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaTab@bmm9sy`}
              buttonsAd={buttonsAd}
              searchType={['base', 'advanced']}
              searchsBaseValue={
                form.isFormInit &&
                form.getFormParams() &&
                form.getFormParams().remark
              }
              setShowSearchAd={this.setShowSearchAd}
              showSearchAd={showSearchAd}
              hideSearchAd={this.hideSearchAd}
              searchsAd={CoworkUtil.getSearchs(form, conditioninfo, () => {
                coworkCollectStore.setShowSearchAd(false);
                coworkCollectStore.doTableLoading();
              })}
              onSearch={this.onSearch}
              onSearchChange={this.onSearchChange}
            />
            <WeaTable
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaTable@nmlx7s`}
              comsWeaTableStore={comsWeaTableStore}
              loading={loading}
              sessionkey={sessionkey}
              needScroll={true}
              hasOrder={true}
              onOperatesClick={this.onOperatesClick}
              getColumns={this.getNewColumns}
            />
          </WeaTop>
        </WeaRightMenu>
      </div>
    );
  }

  setShowSearchAd = (bool) => {
    this.props.coworkCollectStore.setShowSearchAd(bool);
  };
  hideSearchAd = () => this.props.coworkCollectStore.setShowSearchAd(false);
  onSearch = () => {
    const {
      coworkCollectStore: { searchParamsAd, doTableLoading },
    } = this.props;
    doTableLoading(searchParamsAd);
  };
  onSearchChange = (v) => {
    this.props.coworkCollectStore.appendFormFields({ remark: v });
  };

  // 右键菜单
  getRightMenu() {
    let _disabled = !this.getTableSelectedValues().length;
    let btns = [];
    btns.push({
      key: 'search',
      icon: <i className="icon-coms-search" />,
      content: getLabel(197, '搜索'),
    });
    btns.push({
      key: 'cancelCollect',
      icon: <i className="icon-coms-Batch-delete" />,
      disabled: _disabled,
      content: getLabel(129753, '取消收藏'),
    });
    btns.push({
      key: 'ShowCustomColumns',
      icon: <i className="icon-coms-Custom" />,
      content: getLabel(382660, '显示定制列'),
    });
    // btns.push({ key: "collection", icon: <i className='icon-coms-Custom'/>, content: '收藏' });
    // btns.push({ key: "help", icon: <i className='icon-coms-Custom'/>, content: '帮助' });
    return btns;
  }

  // 右键菜单事件绑定
  onRightMenuClick = (key) => {
    const { coworkCollectStore } = this.props;
    if (key == 'search') {
      coworkCollectStore.doTableLoading();
      coworkCollectStore.setShowSearchAd(false);
    } else if (key == 'cancelCollect') {
      this.batchCancelCollect();
    } else if (key == 'ShowCustomColumns') {
      const { comsWeaTableStore, sessionkey } = toJS(coworkCollectStore);
      comsWeaTableStore.setColSetVisible(sessionkey, true);
      comsWeaTableStore.tableColSet(sessionkey, true);
    }
  };

  onTabSearch = () => {
    const { coworkCollectStore } = this.props;
    coworkCollectStore.setShowSearchAd(false);
    coworkCollectStore.doTableLoading();
  };
  onTabReset = () => {
    const { coworkCollectStore } = this.props;
    coworkCollectStore.clearFormFields();
  };
  onTabCancel = () => {
    const { coworkCollectStore } = this.props;
    coworkCollectStore.setShowSearchAd(false);
  };

  // 表格单元格转义
  onOperatesClick = (record, index, operate, flag) => {
    if (flag == 0) {
      // 取消收藏
      let collectIds = record.cid;
      this.executeButtonMethod('batchCancelCollect', collectIds);
    }
  };

  onRemarkClick = (e) => {
    if (e.target.nodeName === 'IMG') {
      let img = e.target;
      img.setAttribute('data-imgsrc', img.src);
      img.setAttribute('class', 'formImgPlay');
      viewer(e);
    }
  };

  // 自定义过滤渲染
  getNewColumns = (columns) => {
    let newColumns = '';
    newColumns = columns.map((column) => {
      let newColumn = column;
      newColumn.render = (text, record) => {
        // 前端元素转义
        let valueSpan =
          record[`${newColumn.dataIndex}span`] !== undefined
            ? record[`${newColumn.dataIndex}span`]
            : record[newColumn.dataIndex];
        let url = '';
        if (newColumn.dataIndex == 'coworkname') {
          url = CoworkUtil.getViewCoworkUrl(record.coworkid);
        } else if (newColumn.dataIndex == 'floorNum') {
          url = CoworkUtil.getViewCoworkOfFloorNnmUrl(
            record.coworkid,
            record.floorNum,
          );
        }
        if (newColumn.dataIndex === 'remark') {
          return (
            <div
              className={'cowork-tablename-remark wea-url'}
              dangerouslySetInnerHTML={{ __html: valueSpan }}
              onClick={this.onRemarkClick}
            />
          );
        }
        return url == '' ? (
          <div
            className={`cowork-tablename-${newColumn.dataIndex} wea-url`}
            dangerouslySetInnerHTML={{ __html: valueSpan }}
          />
        ) : (
          <div
            className="wea-url-name"
            style={{ cursor: 'pointer' }}
            title={text}
            onClick={() => {
              window.open(url);
            }}
            dangerouslySetInnerHTML={{ __html: valueSpan }}
          />
        );
      };
      return newColumn;
    });
    return newColumns;
  };

  // 执行搜索方法（也可用于刷新table）
  executeSearch = () => {
    const { coworkCollectStore } = this.props;
    coworkCollectStore.setShowSearchAd(false);
    coworkCollectStore.doTableLoading();
  };

  // 获得table选中行的主键值数组。若没选中任何一条，返回空数组
  getTableSelectedValues() {
    const { coworkCollectStore } = this.props;
    const { comsWeaTableStore } = coworkCollectStore;
    let values = comsWeaTableStore.selectedRowKeysAllPages;
    return values;
  }

  // 取消收藏
  batchCancelCollect = () => {
    this.executeButtonMethod('batchCancelCollect');
  };
  executeButtonMethod(type, values) {
    const { coworkCollectStore } = this.props;
    if (!values) {
      values = this.getTableSelectedValues();
    }
    let reloadTable = this.executeSearch;

    switch (type) {
      case 'batchCancelCollect': {
        confirm({
          title: getLabel(4916, '确认要取消收藏所选中的内容？', 'note'),
          content: '',
          onOk() {
            coworkCollectStore.cancelCoworkCollect(
              {
                collectIds: values,
              },
              reloadTable,
            );
          },
          onCancel() {},
        });
        break;
      }
    }
  }

  // top中的按钮
  getTopButtons() {
    let values = this.getTableSelectedValues();
    return [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@q1iv4j@cancelCollect`}
        type="primary"
        disabled={!values.length}
        onClick={this.batchCancelCollect}
      >
        {getLabel(129753, '取消收藏')}
      </Button>,
    ];
  }
}

export default WeaTools.tryCatch(
  React,
  props => (
    <WeaErrorPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaErrorPage@61fhn6`}
      msg={
        props.error
          ? props.error
          : getLabel(186, '对不起，该页面异常，请联系管理员！', 'error')
      }
    />
  ),
  { error: '' },
)(Collect);
